package cn.jiangjiesheng.testdemo;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
// 当存在某个类时，此自动配置类才会生效
@ConditionalOnClass(value = {DemoService.class})
// 导入我们自定义的配置类,供当前类使用
@EnableConfigurationProperties(value = DemoProperties.class)
// 只有非web应用程序时此自动配置类才会生效
@ConditionalOnWebApplication
// 判断demo.config.flag的值是否为“true”， matchIfMissing = true：没有该配置属性时也会正常加载
@ConditionalOnProperty(prefix = "demo.config", name = "flag", havingValue = "true", matchIfMissing = true)
public class DemoAutoConfiguration {

    /**
     * @param demoProperties 直接方法签名入参注入DemoProperties,也可以使用属性注入
     * @return DemoService 类
     */
    @Bean
    @ConditionalOnMissingBean(DemoService.class)
    //@ConditionalOnProperty(prefix = "demo.config", name = "flag", havingValue = "true", matchIfMissing = true)
    public DemoService demoService(DemoProperties demoProperties) {
        DemoService demoService = new DemoService();
        //把获取的信息注入
        demoService.setName(demoProperties.getName());
        demoService.setAge(demoProperties.getAge());
        return demoService;
    }
}
